package com.jinlejia.erp.ui.mine.myinfo;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityMyInfoBinding;
import com.jinlejia.erp.ui.common.LogoutDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.StringUtil;
import com.lab.Lab;
import com.yalantis.ucrop.UCrop;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.File;
import java.util.Map;

import jp.wasabeef.glide.transformations.BlurTransformation;
import me.nereo.multi_image_selector.MultiImageSelector;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 我的信息（Activity）
 */

public class MyInfoActivity extends AppCompatActivity {

    private static final int REQUEST_SELECT_PICTURE = 0x01;
    private LogoutDialog dialog;

    private ActivityMyInfoBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //状态栏透明化 必须在setContentView之前
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_my_info);
        binding.setEvent(this);
        EventBus.getDefault().register(this);
        initView();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        dialog = new LogoutDialog(this);
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        dialog.setConfirmListener(() -> OutLogin());
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.out_login:
                dialog.show();
                break;
            case R.id.back_btn:
                finish();
                break;
            case R.id.image_header:
                //图片选择器
                MultiImageSelector.create(MyInfoActivity.this)
                        .showCamera(true)
                        .count(1)
                        .single()
                        .multi()
                        .start(this, REQUEST_SELECT_PICTURE);
                break;
        }
    }

    /**
     * 退出登录
     */
    public void OutLogin() {

        OkHttpUtils
                .postString()
                .url(ApiConfig.OUT_LOGIN)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content("")
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        Lab.userLifecycle().onLogout(MyInfoActivity.this);
                        finish();
                    }

                });
    }

    /**
     * 获取数据
     */
    public void getData() {
        OkHttpUtils
                .get()
                .url(ApiConfig.PERSONAL_INFO)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(MyInfoActivity.this, response, null)) {
                            final JSONObject object = JSON.parseObject(response.get("data").toString());
                            binding.infoName.setText(StringUtil.valueOf(object.get("name")));
                            binding.infoPhone.setText(StringUtil.valueOf(object.get("tel")));
                            binding.infoEmail.setText(!TextUtils.isEmpty(StringUtil.valueOf(object.get("email"))) ? object.get("email").toString() : "");
                            binding.infoJobPosition.setText(StringUtil.valueOf(object.get("titleLevel")));
                            binding.infoStoreGroup.setText(StringUtil.valueOf(object.get("deptName")));
                            if (!TextUtils.isEmpty(object.get("imageUrl").toString())) {
                                Glide.with(MyInfoActivity.this.getApplication()).load(ApiConfig.HEADER_URL().concat(object.get("imageUrl").toString()))
                                        .placeholder(R.mipmap.ic_role_head).error(R.mipmap.ic_role_head).into(binding.imageHeader);
                                Glide.with(MyInfoActivity.this.getApplication()).load(ApiConfig.HEADER_URL().concat(object.get("imageUrl").toString()))
                                        .transform(new BlurTransformation(MyInfoActivity.this, 6, 1))  // “23”：设置模糊度(在0.0到25.0之间)，默认”25";"4":图片缩放比例,默认“1”。
                                        .into(binding.blurBg);
                            } else {
                                binding.imageHeader.setImageResource(R.mipmap.ic_role_head);
                                binding.blurBg.setImageResource(R.color.colorPrimary);
                            }
                        }
                    }
                });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_SELECT_PICTURE) {
                Uri uri = Uri.fromFile(new File(data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT).get(0)));
                startCropActivity(uri);
            }
            if (requestCode == UCrop.REQUEST_CROP) {
                handleCropResult(data);
            }
        }

        if (resultCode == UCrop.RESULT_ERROR) {
            handleCropError(data);
        }
    }

    private void startCropActivity(@NonNull Uri uri) {

        String destinationFileName = System.currentTimeMillis() + ".jpg";

        UCrop uCrop = UCrop.of(uri, Uri.fromFile(new File(getCacheDir(), destinationFileName)));

        uCrop = advancedConfig(uCrop);

        uCrop.start(MyInfoActivity.this);
    }

    /**
     * Sometimes you want to adjust more options, it's done via {@link UCrop.Options} class.
     *
     * @param uCrop - ucrop builder instance
     * @return - ucrop builder instance
     */
    private UCrop advancedConfig(@NonNull UCrop uCrop) {
        UCrop.Options options = new UCrop.Options();

        options.withAspectRatio(1, 1);
        options.setHideBottomControls(true);//底部菜单 true 隐藏
        options.setFreeStyleCropEnabled(false);//设置裁剪框是否能移动


        return uCrop.withOptions(options);
    }

    private void handleCropResult(@NonNull Intent result) {
        final Uri resultUri = UCrop.getOutput(result);
        if (resultUri != null) {
//            ResultActivity.startWithUri(SampleActivity.this, resultUri);
            ShowCropperActivity.startWithUri(MyInfoActivity.this, resultUri);
        }
    }

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    private void handleCropError(@NonNull Intent result) {
        final Throwable cropError = UCrop.getError(result);
        if (cropError != null) {
            Toast.makeText(MyInfoActivity.this, cropError.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(MyInfoActivity.this, "意外错误", Toast.LENGTH_SHORT).show();
        }
    }

    @Subscriber(tag = "IMG_UPLOAD_HEADER")
    public void Updata(String url) {
        getData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}


